package org.restoran.controller.web;

import org.restoran.model.Table;
import org.restoran.service.TableService;
import org.restoran.util.Utills;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * Created with IntelliJ IDEA.
 * User: Andrew Kononenko
 * Date: 19.11.13
 * Time: 8:52
 */

@Controller
@RequestMapping(value="/table", method = RequestMethod.GET, consumes = {"text/plain", "application/*"})
public class DeskController extends AbstractController {

    public static Logger logger = LoggerFactory.getLogger(DeskController.class);

    private final TableService tableService;

    @Autowired
    public DeskController(TableService tableService) {
        this.tableService = tableService;
    }

    @RequestMapping
    public ResponseEntity<String> findAll()
    {
        Iterable<Table> tables = tableService.findAll();
        Collection<Table> collection = Utills.collection(tables);

        String s = tableService.parseToJson(collection);
        return new ResponseEntity<>(success(s), HttpStatus.OK);
    }


    @RequestMapping(value = "/{id}")
    public @ResponseBody String getId(
            @PathVariable("id")
            Integer id)
    {
        Table desks = tableService.findOne(id);
        if(desks != null) {

            logger.debug("ger tables {}", desks);

            return success(tableService.parseToJson(desks));
        } else {
            return error();
        }
    }



    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity<String> updateDesk(
            @RequestBody(required = true)
            String body)
    {
        Table editable = tableService.parseFromJson(body, Table.class);

        logger.debug("deserialize table {} from json, and update", editable, body);

        Table saved = tableService.save(editable);
        return new ResponseEntity<>(success(tableService.parseToJson(saved)), HttpStatus.OK);
    }



    @RequestMapping(value="/{tableId}", method = RequestMethod.DELETE)
    public ResponseEntity<String> delete(
            @PathVariable("tableId")
            Integer tableId)
    {
        tableService.delete(tableId);

        return new ResponseEntity<>(success(), HttpStatus.OK);
    }



}
